<?php

if ( ! function_exists('form_level_dropdown')) {
	function form_level_dropdown($name = '', $options = array(), $selected = '') {
		if($selected == '0') {
			$prefix = "<select id='$name' name='$name'><option value='0'>顶级栏目</option>";
		} 
		else {
			$prefix = "<select id='$name' name='$name'><option value='-1'>请选择栏目</option>";	
		}
		return $prefix . chlid_option( $options, $selected ) . "</select>";
	}
}

if ( ! function_exists('chlid_option')) {
	function chlid_option($options, $selected = '', $parent_id = 0, $rank = 0) {
		static $content;
		foreach( $options as $value ) {
			$space_line = "";
			for( $i = 0; $i < $rank; $i++ ){
				$space_line .= "&nbsp;&nbsp;&nbsp;&nbsp;";
			}
			
			if( $value['parent_id'] == $parent_id ){
				if( $value['id'] == $selected ) {
					$content .= "<option value='". $value['id'] ."' selected>". $space_line . $value['name'] ."</option>";	
				}
				else {
					$content .= "<option value='". $value['id'] ."'>". $space_line . $value['name'] ."</option>";
				}
				chlid_option( $options, $selected, $value['id'], $rank + 1 );
			}		
		}
		return $content;
	}
}

if ( ! function_exists('form_dropdown'))
{
	function form_dropdown($name = '', $options = array(), $selected = array(), $extra = '')
	{
		if ( ! is_array($selected))
		{
			$selected = array($selected);
		}

		// If no selected state was submitted we will attempt to set it automatically
		if (count($selected) === 0)
		{
			// If the form name appears in the $_POST array we have a winner!
			if (isset($_POST[$name]))
			{
				$selected = array($_POST[$name]);
			}
		}

		if ($extra != '') $extra = ' '.$extra;

		$multiple = (count($selected) > 1 && strpos($extra, 'multiple') === FALSE) ? ' multiple="multiple"' : '';

		$form = '<select id="'.$name.'" name="'.$name.'"'.$extra.$multiple.">\n";
	
		foreach ($options as $key => $val)
		{
			$key = (string) $key;

			if (is_array($val))
			{
				$form .= '<optgroup label="'.$key.'">'."\n";

				foreach ($val as $optgroup_key => $optgroup_val)
				{
					$sel = (in_array($optgroup_key, $selected)) ? ' selected="selected"' : '';

					$form .= '<option value="'.$optgroup_key.'"'.$sel.'>'.(string) $optgroup_val."</option>\n";
				}

				$form .= '</optgroup>'."\n";
			}
			else
			{
				$sel = (in_array($key, $selected)) ? ' selected="selected"' : '';

				$form .= '<option value="'.$key.'"'.$sel.'>'.(string) $val."</option>\n";
			}
		}

		$form .= '</select>';

		return $form;
	}
}
?>